package com.yida.wy.basic.controller.common;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.mybatisflex.core.query.QueryWrapper;
import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.exception.ServiceException;
import com.yida.common.core.utils.DateUtils;
import com.yida.common.core.utils.StringUtils;
import com.yida.common.core.utils.poi.ExcelUtil;
import com.yida.common.core.web.controller.BaseController;
import com.yida.common.core.web.domain.AjaxResult;
import com.yida.common.core.web.page.TableDataInfo;
import com.yida.common.log.annotation.Log;
import com.yida.common.log.enums.BusinessType;
import com.yida.common.security.annotation.RequiresPermissions;
import com.yida.gwj.api.domain.GwjFinanceAccountDetail;
import com.yida.gwj.api.service.RemoteGwjFinanceService;
import com.yida.wy.common.domain.WyBaseBuild;
import com.yida.wy.common.domain.WyBaseCommunity;
import com.yida.wy.common.domain.WyBaseHouse;
import com.yida.wy.common.domain.WyBaseOwner;
import com.yida.wy.common.domain.dto.WyBaseCommunityListDTO;
import com.yida.wy.common.domain.dto.WyBaseHouseDTO;
import com.yida.wy.common.domain.dto.WyBaseHouseSstatisticsDTO;
import com.yida.wy.common.domain.request.WyBaseBuildRequest;
import com.yida.wy.common.domain.request.WyBaseCommunityQueryRequest;
import com.yida.wy.common.domain.request.WyBaseHouseRequest;
import com.yida.wy.common.enums.WyBusinessFlagType;
import com.yida.wy.common.enums.WyCheckAccountStatus;
import com.yida.wy.common.enums.WyCheckAccountType;
import com.yida.wy.common.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import static com.yida.wy.common.domain.table.WyBaseBuildTableDef.WY_BASE_BUILD;
import static com.yida.wy.common.domain.table.WyBaseCommunityTableDef.WY_BASE_COMMUNITY;

/**
 * 基础数据查询模块
 * 
 * @author hmh
 * @date 2022-11-15
 */
@RestController
@RequestMapping("/baseData")
@Api(tags = "基础数据查询模块")
public class WyBaseDataController extends BaseController {

    @Autowired
    private IWyBaseCommunityService communityService;

    @Autowired
    private IWyBaseHouseService houseService;

    @Autowired
    private IWyBaseBuildService buildService;

    @Autowired
    private IWyBaseOwnerService ownerService;

    @Resource
    private IWyBaseBusinessService businessService;

    @Resource
    private RemoteGwjFinanceService remoteGwjFinanceService;

    /**
     * 根据小区ID查询小区信息 lqq
     *
     * @param communityIds 小区ID
     * @return /
     */
    @ApiOperation("根据小区ID查询小区信息")
    @PostMapping("/communitySelect")
    public AjaxResult communitySelect(@RequestBody Long[] communityIds) {
        if (StringUtils.isEmpty(communityIds)) {
            AjaxResult.success(new ArrayList<WyBaseCommunityListDTO>());
        }
        return AjaxResult.success(communityService.selectCommunityDtoList(new WyBaseCommunityQueryRequest() {
            {
                setCommunityIds(communityIds);
            }
        }));
    }

    /**
     * 查询基础楼栋列表(选择楼栋) lqq
     * <p>
     * build-info > buildInfo
     *
     * @param buildRequest 请求参数
     * @return /
     */
    @ApiOperation("查询基础楼栋列表(选择楼栋)")
    @PostMapping("/buildInfo")
    public TableDataInfo buildInfo(@Validated @RequestBody WyBaseBuildRequest buildRequest) {
        startPage();
        List<WyBaseBuild> list = buildService.selectGwjBaseBuildDetailList(buildRequest);
        return getDataTable(list);
    }

    /**
     * 查询小区详情 lqq
     *
     * @param buildRequest 请求参数
     * @return /
     */
    @ApiOperation("查询小区详情")
    @PostMapping("/communityInfo")
    public AjaxResult communityInfo(@Validated @RequestBody WyBaseBuildRequest buildRequest) {
        return AjaxResult.success(communityService.selectGwjBaseCommunityDetail(buildRequest));
    }

    /**
     * 查询基础小区列表(根据项目名称模糊查询项目) lqq
     *
     * @param areaId 地区ID
     * @param name 小区名
     * @return /
     */
    @ApiOperation("查询基础小区列表(根据项目名称模糊查询项目)")
    @GetMapping("/communityList/name")
    public AjaxResult queryCommunityListByName(Long areaId, String name) {
        WyBaseCommunity baseCommunity = new WyBaseCommunity();
        baseCommunity.setCommunityName(name);
        baseCommunity.setAreaId(areaId);
        List<WyBaseCommunity> list = communityService.selectCommunityList(baseCommunity);
        list = list.stream().sorted(Comparator.comparing(WyBaseCommunity::getCommunityId, Comparator.nullsFirst(Long::compareTo))).collect(Collectors.toList());
        return AjaxResult.success(list);
    }

    /**
     * 查询基础小区列表(根据地区编号查询项目)
     */
    @ApiOperation("查询基础小区列表(根据地区编号查询项目)")
    @GetMapping("/communityList")
    public TableDataInfo list(WyBaseCommunity baseCommunity) {
        if (StringUtils.isNull(baseCommunity.getAreaId())) {
            throw new ServiceException("查无地区，请选择后查询!");
        }
        startPage();
        List<WyBaseCommunity> list = communityService.selectCommunityList(baseCommunity);
        return getDataTable(list);
    }

    /**
     * 查询基础小区列表(根据条件返回全匹配项目) 20221208 hmh
     */
    @ApiOperation("查询基础小区列表(根据条件返回全匹配项目) ")
    @GetMapping("/communityList/query/")
    public AjaxResult listByName(WyBaseCommunity baseCommunity) {
        List<WyBaseCommunity> list = communityService.selectCommunityList(baseCommunity);
        return AjaxResult.success(list);
    }

    /**
     * 查询基础小区列表(根据街道编号查询项目)
     */
    @ApiOperation("查询基础小区列表(根据街道编号查询项目)")
    @GetMapping("/communityList/street/{streetId}")
    public AjaxResult queryCommunityListByStreetId(@PathVariable Long streetId) {
        List<WyBaseCommunity> list = communityService.list(QueryWrapper.create().where(WY_BASE_COMMUNITY.STREET_ID.eq(streetId)));
        // 根据项目ID进行排序
        list = list.stream().sorted(Comparator.comparing(WyBaseCommunity::getCommunityId, Comparator.nullsFirst(Long::compareTo))).collect(Collectors.toList());
        return AjaxResult.success(list);
    }

    /**
     * 查询楼栋列表(根据项目编号查询楼栋)
     */
    @ApiOperation("查询楼栋列表(根据项目编号查询楼栋)")
    @GetMapping("/buildList/community/{communityId}")
    public AjaxResult queryBuildListByCommunityId(@PathVariable Long communityId) {
        List<WyBaseBuild> list = buildService.list(QueryWrapper.create().where(WY_BASE_BUILD.COMMUNITY_ID.eq(communityId)));
        return AjaxResult.success(list);
    }

    /**
     * 根据地区查询房屋数据
     *
     * @param areaId 地区ID
     * @return /
     */
    @ApiOperation("根据地区查询房屋数据")
    @GetMapping("/houseList/area/{areaId}")
    public TableDataInfo queryHouseListByAreaId(@PathVariable Long areaId) {
        startPage();
        WyBaseHouse baseHouse = new WyBaseHouse();
        baseHouse.setAreaId(areaId);
        List<WyBaseHouse> list = queryHouseList(baseHouse);
        return getDataTable(list);
    }
    //
    // /**
    // * 根据街道查询房屋数据
    // *
    // * @param streetId 街道ID
    // * @return /
    // */
    // @GetMapping("/houseList/street/{streetId}")
    // public TableDataInfo queryHouseListByStreetId(@PathVariable Long streetId) {
    // startPage();
    // BaseHouse baseHouse = new BaseHouse();
    // baseHouse.setStreetId(streetId);
    // List<BaseHouse> list = queryHouseList(baseHouse);
    // return getDataTable(list);
    // }
    //
    // /**
    // * 根据小区查询房屋数据
    // *
    // * @param communityId 小区ID
    // * @return /
    // */
    // @GetMapping("/houseList/community/{communityId}")
    // public TableDataInfo queryHouseListByCommunityId(@PathVariable Long communityId) {
    // startPage();
    // List<BaseHouseDTO> list = houseService.selectHouseListByCommunityId(communityId);
    // return getDataTable(list);
    // }
    //
    // /**
    // * 根据楼栋标识码查询房屋数据
    // *
    // * @param buildCode 楼栋标识码
    // * @return /
    // */
    // @GetMapping("/houseList/build/{buildCode}")
    // public TableDataInfo queryHouseListByBuildId(@PathVariable Long buildCode) {
    // startPage();
    // BaseHouse baseHouse = new BaseHouse();
    // baseHouse.setBuildCode(buildCode);
    // List<BaseHouse> list = queryHouseList(baseHouse);
    // return getDataTable(list);
    // }

    // /**
    // * 根据条件查询房屋数据列表
    // *
    // * @param baseHouse /
    // * @return /
    // */
    private List<WyBaseHouse> queryHouseList(WyBaseHouse baseHouse) {
        return houseService.selectGwjBaseHouseList(baseHouse);
    }

    /**
     * 根据条件查询房屋信息
     *
     * @param houseRequest 房屋请求数据
     * @return
     */
    @ApiOperation("根据条件查询房屋信息")
    @PostMapping("/houseList")
    @RequiresPermissions("gwj:basis:data:query")
    public TableDataInfo queryHouseListByParam(@RequestBody WyBaseHouseRequest houseRequest) {
        startPage();
        List<WyBaseHouseDTO> list = houseService.queryGwjBaseHouseListByParam(houseRequest);
        list.forEach(h -> {
            // 可用余额=余额-冻结
            h.setUseableCurrentMoney((StringUtils.isNull(h.getCurrentMoney()) ? BigDecimal.ZERO : h.getCurrentMoney()).subtract((StringUtils.isNull(h.getBlockedMoney()) ? BigDecimal.ZERO : h.getBlockedMoney())));
            // 合计金额（本利）=余额+利息
            h.setTotalMoney((StringUtils.isNull(h.getCurrentMoney()) ? BigDecimal.ZERO : h.getCurrentMoney()).add((StringUtils.isNull(h.getInterestMoney()) ? BigDecimal.ZERO : h.getInterestMoney())));
            // 计算缴存面积
            h.setDepositSize(null != h.getActualSize() && !new BigDecimal("0.00").equals(h.getActualSize()) ? h.getActualSize() : null != h.getForecastSize() && !new BigDecimal("0.00").equals(h.getForecastSize()) ? h.getForecastSize() : new BigDecimal("0.00"));

        });
        return getDataTable(list);

    }

    /**
     * 根据条件查询房屋统计信息
     * 
     * 20230724
     * 
     * hmh
     *
     * @param houseRequest 房屋请求数据
     * @return
     */
    @ApiOperation("根据条件查询房屋信息")
    @PostMapping("/houseStatistics")
    @RequiresPermissions("gwj:basis:data:query")
    public AjaxResult queryGwjBaseHouseStatisticsByParam(@RequestBody WyBaseHouseRequest houseRequest) {

        WyBaseHouseSstatisticsDTO gwjBaseHouseSstatisticsDTO = houseService.queryGwjBaseHouseStatisticsByParam(houseRequest);
        // 数据库转换后暂时取消
        // if (StringUtils.isNull(gwjBaseHouseSstatisticsDTO)) {
        // return AjaxResult.success(new GwjBaseHouseSstatisticsDTO() {
        // {
        // setTotalForecastSize(BigDecimal.ZERO);
        // setTotalActualSize(BigDecimal.ZERO);
        // setTotalDepositMoney(BigDecimal.ZERO);
        // setTotalUsedMoney(BigDecimal.ZERO);
        // setTotalAddedMoney(BigDecimal.ZERO);
        // setTotalBlockedMoney(BigDecimal.ZERO);
        // setTotalInterestMoney(BigDecimal.ZERO);
        // setTotalCurrentMoney(BigDecimal.ZERO);
        // setTotalHousingPrice(BigDecimal.ZERO);
        // setTotalDepositSize(BigDecimal.ZERO);
        // setTotalUseableCurrentMoney(BigDecimal.ZERO);
        // setTotalMoney(BigDecimal.ZERO);
        // }
        // });
        // }
        // 总可用余额=总余额-总冻结
        gwjBaseHouseSstatisticsDTO.setTotalUseableCurrentMoney((StringUtils.isNull(gwjBaseHouseSstatisticsDTO.getTotalCurrentMoney()) ? BigDecimal.ZERO : gwjBaseHouseSstatisticsDTO.getTotalCurrentMoney()).subtract((StringUtils.isNull(gwjBaseHouseSstatisticsDTO.getTotalBlockedMoney()) ? BigDecimal.ZERO : gwjBaseHouseSstatisticsDTO.getTotalBlockedMoney())));
        // 合计金额（本利）=余额+利息
        gwjBaseHouseSstatisticsDTO.setTotalMoney((StringUtils.isNull(gwjBaseHouseSstatisticsDTO.getTotalCurrentMoney()) ? BigDecimal.ZERO : gwjBaseHouseSstatisticsDTO.getTotalCurrentMoney()).add((StringUtils.isNull(gwjBaseHouseSstatisticsDTO.getTotalInterestMoney()) ? BigDecimal.ZERO : gwjBaseHouseSstatisticsDTO.getTotalInterestMoney())));
        // 缴存面积 有现房拿现房，没现房拿期房 坑爹
        BigDecimal totalDepositSize = gwjBaseHouseSstatisticsDTO.getTotalActualSize().compareTo(BigDecimal.ZERO) == 0 ? gwjBaseHouseSstatisticsDTO.getTotalForecastSize() : gwjBaseHouseSstatisticsDTO.getTotalActualSize();
        gwjBaseHouseSstatisticsDTO.setTotalDepositSize(totalDepositSize);
        return AjaxResult.success(gwjBaseHouseSstatisticsDTO);
    }

    /**
     * 业主缴存根据条件查询房屋信息
     *
     * @param houseRequest 房屋请求数据
     * @return
     */
    @ApiOperation("业主缴存根据条件查询房屋信息")
    @PostMapping("/ownerHouseList")
    @RequiresPermissions("gwj:basis:data:query")
    public TableDataInfo queryOwnerHouseListByParam(@RequestBody WyBaseHouseRequest houseRequest) {
        startPage();
        List<WyBaseHouseDTO> list = houseService.queryGwjBaseHouseListByParam(houseRequest);
        list.forEach(h -> {
            // 可用余额=余额-冻结
            h.setUseableCurrentMoney((StringUtils.isNull(h.getCurrentMoney()) ? BigDecimal.ZERO : h.getCurrentMoney()).subtract((StringUtils.isNull(h.getBlockedMoney()) ? BigDecimal.ZERO : h.getBlockedMoney())));
            // 合计金额（本利）=余额+利息
            h.setTotalMoney((StringUtils.isNull(h.getCurrentMoney()) ? BigDecimal.ZERO : h.getCurrentMoney()).add((StringUtils.isNull(h.getInterestMoney()) ? BigDecimal.ZERO : h.getInterestMoney())));
            // 计算缴存面积
            h.setDepositSize(null != h.getActualSize() && !new BigDecimal("0.00").equals(h.getActualSize()) ? h.getActualSize() : null != h.getForecastSize() && !new BigDecimal("0.00").equals(h.getForecastSize()) ? h.getForecastSize() : new BigDecimal("0.00"));
        });
        return getDataTable(list);
    }

    /**
     * 根据条件查询房屋信息进行导出
     */
    // @RequiresPermissions("gwj:basis:data:export")
    @Log(title = "地区管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export/house")
    @ApiOperation("根据条件查询房屋信息进行导出")
    public void export(HttpServletResponse response, @RequestBody WyBaseHouseRequest houseRequest) {
        System.out.println("houseRequest:" + JSON.toJSONString(houseRequest));
        Integer exportType = 0;
        if (houseRequest.getExportType() != null) {
            exportType = houseRequest.getExportType();
        }
        if (exportType == 1) {
            startPage();
        }
        List<WyBaseHouseDTO> list = houseService.queryGwjBaseHouseListByParam(houseRequest);
        ExcelUtil<WyBaseHouseDTO> util = new ExcelUtil<WyBaseHouseDTO>(WyBaseHouseDTO.class);
        // 字段过滤
        util.hideColumn("communityName", "cardNum", "bankId", "floorNum", "householdNum", "roomNum", "houseCode", "buildCode", "nominalLayer", "depositMoney", "usedMoney", "addedMoney", "blockedMoney", "interestMoney", "housingPrice", "depositSize", "publicFlag", "certificateNum", "publicCreateDate", "areaId", "streetId", "restrictRegisterFlag", "mortRegisterFlag", "transferRegisterFlag", "initialRegisterFlag", "housePredictMortRegisterFlag", "housePredictRegisterFlag",
            "houseContractRegisterFlag", "contractSignFlag", "subscribeFlag", "salePermitFlag");
        util.exportExcel(response, list, DateUtils.getDate() + "房屋数据");
    }

    /**
     * 根据房屋编号与地区编号查询业主信息
     *
     * @param houseCode
     * @param areaId
     * @return
     */
    @GetMapping("/getOwnerByHouseCodeAndAreaId")
    @ApiOperation("根据房屋编号与地区编号查询业主信息")
    public AjaxResult getOwnerByHouseCodeAndAreaId(@RequestParam String houseCode, @RequestParam Long areaId) {
        WyBaseOwner owner = new WyBaseOwner();
        owner.setHouseCode(houseCode);
        owner.setAreaId(areaId);
        return AjaxResult.success(ownerService.selectGwjBaseOwnerList(owner));
    }

    /**
     * @param houseCode 房屋编号
     * @param areaId 地区ID
     * @return /
     */
    @ApiOperation("根据房屋编号与地区编号查询房屋业务日志")
    @GetMapping("/selectHouseBusinessList/{areaId}/{houseCode}")
    public TableDataInfo selectHouseBusinessListByHouseCodeAndAreaId(@PathVariable("houseCode") String houseCode, @PathVariable("areaId") Long areaId) {
        startPage();
        return getDataTable(businessService.selectHouseBusinessListByHouseCodeAndAreaId(houseCode, areaId));
    }

    /**
     * @param houseCode 房屋编号
     * @param areaId 地区ID
     * @return /
     */
    @ApiOperation("根据房屋编号与地区编号查询房屋明细账")
    @GetMapping("/selectHouseDetailList/{areaId}/{houseCode}")
    public TableDataInfo selectHouseDetailListByHouseCodeAndAreaId(@PathVariable("houseCode") String houseCode, @PathVariable("areaId") Long areaId) {
        startPage();
        List<GwjFinanceAccountDetail> list = remoteGwjFinanceService.selectGwjFinanceAccountDetailList(new GwjFinanceAccountDetail() {
            {
                setHouseCode(houseCode);
                setAreaId(areaId);
            }
        }, SecurityConstants.INNER).getData().stream().peek(item -> {
            item.setBizFlagIdStr(WyBusinessFlagType.getInfoByCode(item.getBizFlagId()));
            item.setCheckTypeStr(WyCheckAccountType.getInfoByCode(item.getCheckType()));
            item.setCheckStatusStr(WyCheckAccountStatus.getInfoByCode(item.getCheckStatus()));
        }).collect(Collectors.toList());
        return getDataTable(list);
    }

    /**
     * 查询基础小区列表(根据地区编号查询项目)
     * 
     * 20230715
     * 
     * hmh
     * 
     */
    @ApiOperation("查询基础小区列表(根据地区编号查询项目)")
    @GetMapping("/queryCommunityList")
    public AjaxResult queryCommunityList(WyBaseCommunity baseCommunity) {
        if (StringUtils.isNull(baseCommunity.getAreaId())) {
            throw new ServiceException("查无地区，请选择后查询!");
        }
        JSONArray jsonArray = communityService.queryCommunityList(baseCommunity);
        return AjaxResult.success(jsonArray);
    }
}
